from PIL import Image, ImageDraw, ImageFont
import os
import base64
from zhipuai import ZhipuAI
client = ZhipuAI(api_key="270ea062fd48e631d31ac79585c87d7f.2f6XYjYw9N0oSSJB") # 填写您自己的APIKey

def text_to_image(text, pic_name, font_path='simhei.ttf', font_size=20, text_color=(0, 0, 0), bg_color=(255, 255, 255)):
    # 使用指定字体和大小加载字体
    font = ImageFont.truetype(font_path, font_size)

    # 计算文本尺寸
    lines = text.split('\n')
    max_width = 0
    total_height = 0
    for line in lines:
        bbox = font.getbbox(line)
        line_width = bbox[2] - bbox[0]
        line_height = bbox[3] - bbox[1]
        max_width = max(max_width, line_width)
        total_height += line_height

    # 创建一个空白图像
    img = Image.new('RGB', (max_width + 20, total_height + 20), bg_color)  # 加上边距
    draw = ImageDraw.Draw(img)

    # 在图像上绘制文本
    y_text = 10
    for line in lines:
        bbox = font.getbbox(line)
        line_height = bbox[3] - bbox[1]
        draw.text((10, y_text), line, font=font, fill=text_color)
        y_text += line_height

    # 保存图像
    img.save(pic_name)




def add_newline_every_256_chars(input_string):
    """
    在输入字符串中每150个字符后添加一个换行符。

    :param input_string: 输入的原始字符串
    :return: 处理后的字符串，每180个字符后有一个换行符
    """
    # 使用列表推导式来构建新的字符串
    result = '\n'.join([input_string[i:i+100] for i in range(0, len(input_string), 100)])
    return result


def png_to_base64(file_path):
    """
    读取一个PNG文件并返回其Base64编码。

    :param file_path: PNG文件的路径
    :return: Base64编码的字符串
    """
    try:
        # 以二进制模式打开文件
        with open(file_path, 'rb') as file:
            # 读取文件内容
            file_content = file.read()
            # 将文件内容转换为Base64编码
            base64_encoded = base64.b64encode(file_content).decode('utf-8')
            return base64_encoded
    except FileNotFoundError:
        print(f"文件未找到: {file_path}")
        return None
    except Exception as e:
        print(f"发生错误: {e}")
        return None




def check_keyword_in_string(input_string):
    response = client.chat.completions.create(
    model="glm-4-9b:883342770::ltosovmf",  # 填写需要调用的模型编码
    messages=[
        {"role": "system", "content": "图片中是否有\n  发送数据给NCC\n    这个字符串  如果有返回YES 没有就返回NO"},
        {"role": "user", "content": "图片中是否有\n  发送数据给NCC\n    这个字符串  如果有返回YES 没有就返回NO","images":[input_string]}
      ],
    )
    return  response.choices[0].message.content



def print_file_with_line_numbers(file_path):
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            for line_number, line in enumerate(file, 1):
                #print(add_newline_every_256_chars(line.strip()))
                # 文字转图片
                text_to_image(add_newline_every_256_chars(line.strip()),str(line_number)+".png") 
                str1 = check_keyword_in_string(png_to_base64(str(line_number)+".png"))
                print(str1)


    except FileNotFoundError:
        print(f'Error: The file at path "{file_path}" was not found.')
    except Exception as e:
        print(f'An error occurred: {e}')

# 使用示例
file_path = 'nccdata25'  # 替换为你的文件路径
print_file_with_line_numbers(file_path)

